import React from 'react';
import {Redirect} from 'umi'

import pathToRegexp from 'path-to-regexp';
import Authorized from '@/utils/Authorized';
import { getUserInfo } from '@/utils/userInfo';

interface AuthComponentProps  {
}

const getRouteAuthority = (path: string, routeData: any[]) => {

  let authorities: string[] | string | undefined;
  routeData.forEach(route => {
    // match prefix
    if (pathToRegexp(`${route.path}(.*)`).test(path)) {
      // exact match
      // console.log(route, path, route.path.split(":"), 'route-path')
      const nowRoute = route.path.split(':') && route.path.split(':')[0]

      if (nowRoute && path.startsWith(nowRoute)) {
        authorities = route.authority || authorities;
      }
      // get children authority recursively
      if (route.routes) {
        authorities = getRouteAuthority(path, route.routes) || authorities;
      }
    }
  });
  return authorities;
};

const AuthComponent: React.FC<AuthComponentProps> = ({
  children,
  route = {
    routes: [],
  },
  location = {
    pathname: '',
  },
}) => {
  // const { currentUser } = user;
  const currentUser = getUserInfo();
  const { routes = [] } = route;
  const isLogin = currentUser && currentUser.name;
  // return null;
  // 没有登录跳转到登录，有登录再走权限
  return (
    <Authorized
      authority={getRouteAuthority(location.pathname, routes) || ''}
      noMatch={isLogin ? <Redirect to="/exception/403" /> : <Redirect to="/login" />}
    >
      {children}
    </Authorized>
  );
};

export default AuthComponent;
